//
//  PersonNameEditViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/5/6.
//

#import "PersonNameEditViewController.h"

@interface PersonNameEditViewController ()
@property (weak, nonatomic) IBOutlet UIView *editView;
@property (weak, nonatomic) IBOutlet UITextField *textField;

@end

@implementation PersonNameEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置昵称";
    [((UIButton *)[self addLeftBtn:@"取消"]) addTarget:self action:@selector(cancelPress) forControlEvents:UIControlEventTouchUpInside];
    [((UIButton *)[self addRigthBtn:@"完成"]) addTarget:self action:@selector(finishPress) forControlEvents:UIControlEventTouchUpInside];
    [self.editView setFrame:CGRectMake(0, NavBarHeight + IS_iPhoneX_Top, SCREEN_WIDTH_DEVICE, 50)];
    self.textField.text = self.nameStr;
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.textField becomeFirstResponder];
}

- (void)dealloc{
    [[ServiceRequest sharedService] cancelDataTaskForKey:[NSString stringWithFormat:@"user/%@", [UserManger currentLoggedInUser].platformId]];
}

- (void)cancelPress{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

- (void)finishPress{
    if (self.textField.text.length == 0) {
        [self showHUDAlert:@"昵称不能为空"];
        return;
    }
    [self loadingHUDAlert:@"正在保存"];
    UserInfo *user = [UserManger currentLoggedInUser];
    [[ServiceRequest sharedService] PUTJSON:[NSString stringWithFormat:@"user/%@", user.platformId] parameters:@{@"nickName":self.textField.text} success:^(id responseObject) {
        [self hideHudAlert];
        user.userName = self.textField.text;
        [UserManger setUser:user];
        [self dismissViewControllerAnimated:YES completion:^{
            if (self.RefreshHandle) {
                self.RefreshHandle(self.textField.text);
            }
            [self.view endEditing:YES];
        }];
    } failure:^(NSString *error, NSInteger code) {
        [self showHUDAlert:error];
    }];
    
}

@end
